package com.ucpaas.sms.action.auditorKeyWord;

import com.jsmsframework.audit.entity.JsmsAuditKeywordList;
import com.jsmsframework.audit.service.JsmsAuditKeywordCategoryService;
import com.jsmsframework.audit.service.JsmsAuditKeywordListService;
import com.jsmsframework.common.dto.JsmsPage;
import com.jsmsframework.common.dto.ResultVO;
import com.jsmsframework.common.util.BeanUtil;
import com.ucpaas.sms.action.BaseAction;
import com.ucpaas.sms.dto.AuditKeywordListDTO;
import com.ucpaas.sms.dto.JsmsAutoTemplateDTO;
import com.ucpaas.sms.model.Excel;
import com.ucpaas.sms.service.auditorKeyWord.AuditorKeyWordService;
import com.ucpaas.sms.util.CommonUtil;
import com.ucpaas.sms.util.ConfigUtils;
import com.ucpaas.sms.util.JsmsHanLPUtils;
import com.ucpaas.sms.util.file.ExcelUtils;
import com.ucpaas.sms.util.web.AuthorityUtils;
import com.ucpaas.sms.util.web.StrutsUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 审核关键字列表
 */
@Controller
@Scope("prototype")
@Results({
        @Result(name = "list", location = "/WEB-INF/content/auditKeyword/list/list.jsp"),
        @Result(name = "edit", location = "/WEB-INF/content/auditKeyword/list/edit.jsp")
})
public class AuditKeyWordListAction extends BaseAction {

    private static Logger logger = LoggerFactory.getLogger(AuditKeyWordListAction.class);
    @Autowired
    private AuditorKeyWordService auditorKeyWordService;
    @Autowired
    private JsmsAuditKeywordCategoryService jsmsAuditKeywordCategoryService;
    @Autowired
    private JsmsAuditKeywordListService jsmsAuditKeywordListService;


    /**
     * 审核关键字列表
     *
     * @return
     */
    @Action("/auditKeyword/list")
    public String keyWordsList() {
        Map<String, String> params = StrutsUtils.getFormData();
        String categoryId = StrutsUtils.getParameter("categoryId");
        String kgroupIdStr = StrutsUtils.getParameter("kgroupId");
        Integer kgroupId = null;
        if(StringUtils.isNotBlank(kgroupIdStr)){
            kgroupId = Integer.valueOf(kgroupIdStr);
        }
        //简繁体
        String condition = StrutsUtils.getParameter("condition");
        if(StringUtils.isNotBlank(condition)){
//            params.put("simplifredChineseCondition", HanLP.convertToSimplifiedChinese(condition).trim());
//            params.put("traditionalChineseCondition", HanLP.convertToTraditionalChinese(condition).trim());
            params.put("simplifredChineseCondition", JsmsHanLPUtils.convertToSimplifiedChinese(condition).trim());
            params.put("traditionalChineseCondition", JsmsHanLPUtils.convertToTraditionalChinese(condition).trim());
        }
        JsmsPage<JsmsAuditKeywordList> jsmsPage = CommonUtil.initJsmsPage(params);
        auditorKeyWordService.queryKeywordListKgroup(jsmsPage,kgroupId);
        page = CommonUtil.converterJsmsPage2PageContainer(jsmsPage);

        StrutsUtils.setAttribute("categoryId",categoryId);
        StrutsUtils.setAttribute("kgroupId",kgroupId);
        StrutsUtils.setAttribute("condition",params.get("condition"));
        StrutsUtils.setAttribute("max_export_excel_num", ConfigUtils.max_export_excel_num);

        return "list";
    }



    /**
     * 编辑审核关键字页面
     */
    @Action("/auditKeyword/editpage")
    public String editKeywordsPage() {
        String idStr = StrutsUtils.getParameter("id");

        if (StringUtils.isNotBlank(idStr)){
            Long id = Long.valueOf(idStr);
            JsmsAuditKeywordList keyword = jsmsAuditKeywordListService.getById(id);
            AuditKeywordListDTO model = new AuditKeywordListDTO();
            BeanUtil.copyProperties(keyword,model);
            StrutsUtils.setAttribute("model",model);
        }
        return "edit";
    }
    /**
     * 编辑关键字
     * @return
     */
    @Action("/auditKeyword/edit")
    public void editKeywords() {
        Map<String, String> params = StrutsUtils.getFormData();
        Long userId = AuthorityUtils.getLoginUserId();
        params.put("adminId", String.valueOf(userId));
        ResultVO resultVO = null;
        try {
            resultVO = auditorKeyWordService.updateKeyword(params);
        } catch (ParseException e) {
            resultVO = ResultVO.failure("参数无效, 请稍后再试...");
        }
        StrutsUtils.renderJson(resultVO);
    }


    /**
     * 导出报表
     */
    @Action("/auditorkeyword/keyWordsList/exportkeyword")
    public void exportkeyword() {
        Map<String, String> params = StrutsUtils.getFormData();

        //简繁体
        String condition = StrutsUtils.getParameter("condition");
        if(StringUtils.isNotBlank(condition)){
//            params.put("simplifredChineseCondition", HanLP.convertToSimplifiedChinese(condition).trim());
//            params.put("traditionalChineseCondition", HanLP.convertToTraditionalChinese(condition).trim());
            params.put("simplifredChineseCondition", JsmsHanLPUtils.convertToSimplifiedChinese(condition).trim());
            params.put("traditionalChineseCondition", JsmsHanLPUtils.convertToTraditionalChinese(condition).trim());
        }

        String categoryId = StrutsUtils.getParameter("categoryId");
        String kgroupIdStr = StrutsUtils.getParameter("kgroupId");
        Integer kgroupId = null;
        if(StringUtils.isNotBlank(kgroupIdStr)){
            kgroupId = Integer.valueOf(kgroupIdStr);
        }

        StringBuffer filePath = new StringBuffer(ConfigUtils.save_path);
        if(!ConfigUtils.save_path.endsWith("/")){
            filePath.append("/");
        }
        filePath.append("审核关键字")
                .append(".xls")
                .append("$$$")
                .append(UUID.randomUUID());
        Excel excel = new Excel();
        excel.setFilePath(filePath.toString());
        excel.setTitle("审核关键字");
        StringBuffer buffer = new StringBuffer();
        buffer.append("查询条件：");
        condition = params.get("condition");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  关键字：");
            buffer.append(condition);
            buffer.append(";");
        }
        excel.addRemark(buffer.toString());

        excel.addHeader(20, "序号", "rowNum");
        excel.addHeader(20, "关键字", "keyword");
        excel.addHeader(20, "备注", "remarks");
        excel.addHeader(20, "关键字类别", "categoryName");
        excel.addHeader(20, "关键字组别", "kgroupName");
        excel.addHeader(20, "操作人", "operatorStr");
        excel.addHeader(20, "更新时间", "updateDateStr");

        Map<String, String> formData = StrutsUtils.getFormData();
        List<Map<String, Object>> dataList = auditorKeyWordService.queryExportExcelData(formData);
        excel.setDataList(dataList);
        excel.setShowRownum(false);
        excel.setShowPage(false);
        excel.setShowGridLines(false);
        excel.setShowTitle(false);

        ResultVO resultVO = null;
        try {

            JsmsPage<JsmsAuditKeywordList> jsmsPage = CommonUtil.initJsmsPage(params);
            jsmsPage.setRows(Integer.MAX_VALUE);
            auditorKeyWordService.queryKeywordListKgroup(jsmsPage,kgroupId);
            List<JsmsAutoTemplateDTO> list = new ArrayList<>();
            List result = new ArrayList();
            for (Object temp : jsmsPage.getData()) {
                result.add(BeanUtils.describe(temp));
            }
            if (result == null || result.size() <= 0){
                resultVO = ResultVO.failure("没有数据！先不导出了  ^_^");
//            }else if (result.size() > Integer.valueOf(ConfigUtils.max_export_excel_num)){
            }else if (result.size() > Integer.valueOf(Integer.MAX_VALUE)){
                resultVO =  ResultVO.failure("数据量超过"+ConfigUtils.max_export_excel_num+"，请缩小范围后再导出吧  ^_^");
            }
            excel.setDataList(result);
            if (ExcelUtils.exportExcel(excel)) {
                resultVO = ResultVO.successDefault();
                resultVO.setMsg("报表生成成功");
                resultVO.setData(excel.getFilePath());
            }
        } catch (Exception e) {
//            e.printStackTrace();
            logger.error("报表导出失败",e);
        }
        StrutsUtils.renderJson(resultVO);
    }
}
